package net.coding.li709.materialrefresher.manage;

import com.google.common.reflect.TypeToken;
import net.coding.li709.itemmanagement.manager.ItemManager;
import net.coding.li709.materialrefresher.MaterialRefresher;
import net.coding.li709.materialrefresher.model.Box;
import net.coding.li709.serverbase.utils.ConfigUtils;
import ninja.leaping.configurate.ConfigurationNode;
import ninja.leaping.configurate.objectmapping.ObjectMappingException;
import org.spongepowered.api.item.inventory.ItemStack;

import java.util.*;

public class GiftManager {
    //宝箱名 也是对应的rpg物品名
    private static Map<String, Box> boxMap;

    private static Random r=new Random();

    /**
     * 加载礼包配置
     */
    public static void load() {
        boxMap=new HashMap<>();

        //加载宝箱配置
        loadTreasure();
    }

    public static boolean isBox(String boxName){
        return boxMap.containsKey(boxName);
    }

    private static void loadTreasure() {
        ConfigurationNode treasure = ConfigUtils.loadConfig(MaterialRefresher.ID,"box",false);
        ConfigurationNode node;
        List<String> list;
        Box box;
        int sum;
        int odds;
        for (Object o : treasure.getChildrenMap().keySet()) {
            node = treasure.getNode(o);
            sum=0;
            box=new Box();
            box.setId(o.toString());
            boxMap.put(box.getId(),box);
            for (Object o1 : node.getChildrenMap().keySet()) {
                try {
                    odds=Integer.valueOf(o1.toString());
                    list = node.getNode(o1).getList(TypeToken.of(String.class));
                    box.getItemMap().put(odds,list);
                    sum+=odds;
                } catch (ObjectMappingException e) {
                    e.printStackTrace();
                }
            }
            box.setSum(sum);
        }
    }


    /**
     * 使用宝箱
     */
    public static ItemStack useBox(String boxName) {
        Box box = boxMap.get(boxName);
        //随机数
        int rd = r.nextInt(box.getSum());

        int min=0;
        int max=0;
        for (Integer odds : box.getItemMap().keySet()) {
            max+=odds;
            //在区间
            if (rd>=min&&rd<max){
                return spawnBoxItem(box, odds);
            }
            min+=odds;
        }
        return null;
    }

    /**
     * 给玩家宝箱里的奖品
     */
    private static ItemStack spawnBoxItem(Box box, Integer odds) {
        List<String> list = box.getItemMap().get(odds);
        String split[] = list.get(r.nextInt(list.size())).split("\\*");
        Optional<ItemStack> customItem = ItemManager.getCustomItem(split[0]);
        if (customItem.isPresent()){
            ItemStack itemStack = customItem.get();
            itemStack.setQuantity(Integer.valueOf(split[1]));
            return itemStack;
        }else{
            MaterialRefresher.getLogger().error("找不到宝箱里的物品{}，宝箱：{}",split[0],box.getId());
            return null;
        }
    }


}
